<template>
  <!-- 表格操作页面 -->
  <div class="table-main">
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="搜索内容：">
        <el-input
          v-model="searchValue"
          placeholder="请输入姓名"
          @input="handleSearch"
        />
      </el-form-item>
      <el-form-item label="图片选择器：">
        <el-select v-model="value" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          <img :src="item.label" alt="">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleAdd()">添加</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableList" style="width: 100%">
      <el-table-column label="姓名" width="180">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p>姓名: {{ scope.row.name }}</p>
            <p>住址: {{ scope.row.address }}</p>
            <div slot="reference" class="name-wrapper">
              {{ scope.row.name }}
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="出生日期" width="180">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span style="margin-left: 10px">{{ scope.row.date }}</span>
        </template>
      </el-table-column>
      <!-- 操作按钮触发事件 -->
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加修改信息弹出框 -->
    <el-dialog
      :title="dialogType === 'edit' ? '编辑个人信息' : '添加个人信息'"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <el-form
        ref="form"
        :model="form"
        label-width="100px"
        style="width: 320px"
      >
        <el-form-item label="名字：" prop="name">
          <el-input v-model="form.name" size="mini" placeholder="请输入名字" />
        </el-form-item>
        <el-form-item label="出生日期：" prop="date">
          <el-date-picker
            v-model="form.date"
            type="date"
            placeholder="选择出生日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="家庭住址：" prop="address">
          <el-input v-model="form.address" placeholder="请输入家庭住址" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
// 引入工具库
import { debounce } from "lodash";
// 默认数据
const defaulUser = {
  name: "",
  data: "",
  address: "",
};
export default {
  data() {
    return {
      // 表格数据
      tableData: [
        {
          date: "2016-05-02",
          name: "JavaScript",
          address: "上海市普陀区金沙江路 1518 弄",
        },
        {
          date: "2016-05-02",
          name: "Java",
          address: "上海市普陀区金沙江路 1518 弄",
        },
        {
          date: "2016-05-02",
          name: "PHP",
          address: "上海市普陀区金沙江路 1518 弄",
        },
      ],
      dialogVisible: false,
      // 合并对象
      form: Object.assign({}, defaulUser),
      dialogType: "",
      searchValue: "",
      options: [
        {
          value: "选项1",
          label: "https://profile.csdnimg.cn/3/F/3/3_jinchunzhao123",
        },
        {
          value: "选项2",
          label: "https://devops.aliyun.com/api/images/avatars/14.png",
        },
        {
          value: "选项3",
          label: "蚵仔煎",
        },
        {
          value: "选项4",
          label: "龙须面",
        },
        {
          value: "选项5",
          label: "北京烤鸭",
        },
      ],
      value: "",
    };
  },
  methods: {
    // 编辑按钮
    handleEdit(scope) {
      // 定义弹框的标题
      this.dialogType = "edit";
      this.form = this.deepClone(scope.row);
      console.log(this.form);
      this.dialogVisible = true;
    },
    // 点击删除   { $index, row }  解构scope
    handleDelete({ $index, row }) {
      // 二次确认删除
      this.$confirm("Confirm to remove the role?", "Warning", {
        confirmButtonText: "Confirm",
        cancelButtonText: "Cancel",
        type: "warning",
      })
        // 同步数据处理
        .then(async () => {
          // 数据整合处理  分割

          this.tableData.splice($index, 1);
          this.$message({
            type: "success",
            message: "Delete succed!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
    handleAdd() {
      // 定义弹框的标题
      this.dialogType = "add";
      this.dialogVisible = true;
    },
    // 搜索     防抖处理
    handleSearch: debounce(function () {
      if (this.searchValue) {
        console.log(this.searchValue);
      }
    }, 1000),
    handleSubmit() {
      // 判断是否编辑状态
      const isEdit = this.dialogType === "edit";
      if (isEdit) {
        for (let index = 0; index < this.tableData.length; index++) {
          if (this.tableData[index].key === this.form.key) {
            this.tableData.splice(index, 1, Object.assign({}, this.form));
            break;
          }
        }
      } else {
        // 进入添加状态
        this.tableData.push(this.form);
      }
      // ES6解构数据  输出信息提示添加成功
      const { name, date, address } = this.form;
      this.$notify({
        title: "Success",
        dangerouslyUseHTMLString: true,
        message: `
            <div>姓名: ${name}</div>
            <div>出生日期: ${date}</div>
            <div>地址: ${address}</div>
          `,
        type: "success",
      });
      // 关闭弹框
      this.dialogVisible = false;
    },
    // 深拷贝方法
    deepClone(source) {
      if (!source && typeof source !== "object") {
        throw new Error("error arguments", "deepClone");
      }
      const targetObj = source.constructor === Array ? [] : {};
      Object.keys(source).forEach((keys) => {
        if (source[keys] && typeof source[keys] === "object") {
          targetObj[keys] = deepClone(source[keys]);
        } else {
          targetObj[keys] = source[keys];
        }
      });
      return targetObj;
    },
  },
  computed: {
    // 根据计算属性模糊搜索
    tableList() {
      const searchValue = this.searchValue.toString().trim();
      if (searchValue) {
        const arr = [];
        this.tableData.forEach((v) => {
          if (v.name.indexOf(searchValue) >= 0) {
            arr.push(v);
          }
        });
        return arr;
      }
      return this.tableData;
    },
  },
  watch: {
    dialogVisible(l) {
      if (l === false) {
        this.form = Object.assign({}, defaulUser);
        // 下面这种方式置空数据无效
        // this.$refs.form.resetFields();
      }
    },
  },
};
</script>
